unit ec_controltimer;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, Buttons,
  StdCtrls, Spin, ec_base;

type

  { TECControlTimerFrame }

  TECControlTimerFrame = class(TECBaseFrame)
    MinutesLabel: TLabel;
    SecondsLabel: TLabel;
    MinutesSpinEdit: TSpinEdit;
    SecondsSpinEdit: TSpinEdit;
    TimeGroupBox: TGroupBox;
    OperationRadioGroup: TRadioGroup;
    procedure OperationRadioGroupSelectionChanged(Sender: TObject);
  private
    procedure InitialSetup;

  public
    procedure InitNew; override;
    procedure InitExisting; override;
    procedure MakeResultingCommand; override;
  end;

var
  ECControlTimerFrame: TECControlTimerFrame;

implementation

{$R *.lfm}

uses
  fpjson, constants;

resourcestring
  rsStartTimer = 'Start';
  rsStopTimer = 'Stop';

{ TECControlTimerFrame }

procedure TECControlTimerFrame.OperationRadioGroupSelectionChanged(
  Sender: TObject);
begin
  TimeGroupBox.Visible := OperationRadioGroup.ItemIndex = 0;
end;

procedure TECControlTimerFrame.InitialSetup;
begin
  with OperationRadioGroup.Items do begin
    BeginUpdate;
    Clear;

    Add(rsStartTimer);
    Add(rsStopTimer);

    EndUpdate;
  end;
end;

procedure TECControlTimerFrame.InitNew;
begin
  InitialSetup;

  MinutesSpinEdit.Value := 0;
  SecondsSpinEdit.Value := 0;
  OperationRadioGroup.ItemIndex := 0;
end;

procedure TECControlTimerFrame.InitExisting;
var
  Params: TJSONArray;
  Operation: Integer = 0;
  Time: Integer = 0;
begin
  InitialSetup;

  Params := GetFirstParams;

  if (Params.Count >= 1) and (Params[0].JSONType = jtNumber) then
    Operation := Params.Integers[0];

  if (Params.Count >= 2) and (Params[1].JSONType = jtNumber) then
    Time := Params.Integers[1];

  OperationRadioGroup.ItemIndex := Operation;
  MinutesSpinEdit.Value := Time div 60;
  SecondsSpinEdit.Value := Time mod 60;
end;

procedure TECControlTimerFrame.MakeResultingCommand;
begin
  ResultingCommand := SingleLineResultingCommand(
    CONTROL_TIMER_EC_CODE,
    TJSONArray.Create([
      OperationRadioGroup.ItemIndex,
      MinutesSpinEdit.Value * 60 + SecondsSpinEdit.Value
    ])
  );
end;

end.

